package com.thoughtservice.jspdoc.processors;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thoughtservice.jspdoc.JSPFileList;
import com.thoughtservice.jspdoc.JSPPage;
import com.thoughtservice.jspdoc.RE;
import com.thoughtservice.jspdoc.RESyntaxException;

public class ProcessPageDescription implements DocProcessor{

	private final static Logger LOG = LoggerFactory.getLogger(ProcessPageDescription.class);

	
	public boolean process(JSPPage p, String pc, JSPFileList fileList) throws RESyntaxException {
		LOG.trace("Entering {}", "ProcessPageDescription");
		Object descriptions[] = getPageDesc(1, p, pc, fileList);
		String desc = "";
		for(Object ob : descriptions){
			desc = desc.concat("<br />"+ob.toString());
		}		
		LOG.info("Desc --> {}", desc);
		p.setPageDesc(desc);						
		LOG.trace("Exiting {}","ProcessPageDescription");
	
		return true;
	}
	
	private Object[] getPageDesc(int depth, JSPPage p, String pc, JSPFileList fileList) throws RESyntaxException{
		LOG.trace("Entering {}", "getPageDesc");
		List<String> pageDescriptions  = new ArrayList<String>();
		String[] pageDescriptionsTemp = new String[]{};
		RE re;
		//		re = new RE("<%[:space:]*/\\*\\*[:print:]*?\\*/[:space:]*%>");
		// Does not match anymore with GNU-Regexp
		//re = new RE("<%[:space:]*/\\*\\*.*?\\*/[:space:]*(%>){1}");
		//re = new RE("<%[:space:]*/\\*\\*.*?\\*/[:space:]*%>");
		re = new RE("<%--[:space:]*([:print:]*?)--%>");
		re.match(pc);
		if(depth == 0){
			pageDescriptionsTemp[0] = re.getParen(0);					
		} else {
			pageDescriptionsTemp = re.getAllMatches(pc, 1);
		}		
		for(String pageDesc: pageDescriptionsTemp){
			LOG.info("Descriptions {} Descriptn 1 {}",pageDescriptionsTemp, pageDesc);
			if (pageDesc != null) {
				// Remove open tag
				//re = new RE("<%[:space:]*/\\*\\*");
				re = new RE("<%--[:space:]*");
				pageDesc = re.subst(pageDesc, "");
				re = new RE("[:space:]*--%>");
				pageDesc = re.subst(pageDesc, "");			
				// Remove close tag
				//re = new RE("\\*/[:space:]*%>$");
				re = new RE("[:space:]--%>$");
				pageDesc = re.subst(pageDesc, "");				
				// Remove all the non-printable characters
//					re = new RE("[^.]");
//					pageDesc = re.subst(pageDesc, "");
				
				// Remove comment asteriks
				// This currently removes all asteriks, but it should be smarter as this
				// will remove asteriks which are part of the actual comments.
				re = new RE("\\*");
				pageDesc = re.subst(pageDesc, "");	
				LOG.info("Description after {}", pageDesc);
				pageDescriptions.add(pageDesc);
				           
			}
		}		
		LOG.trace("Exiting {}", "getPageDesc");
		return pageDescriptions.toArray();
	}
}
